package com.cutefool.zero.code.sso.login;

import com.cutefool.core.account.Account;
import com.cutefool.core.account.LoginAccountService;
import com.cutefool.core.kits.jackson.Jackson;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Component
public class Oauth2LoginAccountService implements LoginAccountService<Account> {

    @Override
    public Optional<Account> get() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return Optional.empty();
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof Jwt jwt) {
            Map<String, Object> claims = jwt.getClaims();
            return Jackson.toBean(claims, Account.class);
        }
        return Optional.empty();
    }
}
